package com.clayecloud.common.utils;


import com.clayecloud.common.expection.FileNotExitException;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.RSA;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.*;
import java.security.KeyPair;

@Component
public class RSAUtil {

    /**
    * 从项目的资源文件夹下读取key文件，参数为文件名，返回经过 Base64 解码后的密钥
    */
    public static byte[] getKeyFromFile(String file) throws IOException {
        ClassPathResource classPathResource=new ClassPathResource(file);
        if (!classPathResource.getFile().exists()) {
            throw new FileNotExitException();
        }
        InputStream inputStream= null;
        try {
            inputStream = classPathResource.getInputStream();
            ByteArrayOutputStream bio=new ByteArrayOutputStream(1024);
            byte[] bytes=new byte[1024];
            int n;
            while ((n=inputStream.read(bytes))!=-1){
                bio.write(bytes,0,n);
            }
            return Base64.decodeBase64(bio.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
    * 创建Rsa公钥和私钥
     * 生成的是1024位的,新版本的jjwt要求2048位,
     *
    */
    public static void generateRsaKeyPair() throws IOException {
        KeyPair pair = SecureUtil.generateKeyPair("RSA",2048);
        RSA rsa = new RSA(pair.getPrivate(),pair.getPublic());
        FileOutputStream outputStream;                                  //创建文件输出流

        ClassPathResource priPath=new ClassPathResource("static/key.pri");     //在Resource目录下创建"key.pri"文件
        ClassPathResource pubPath=new ClassPathResource("static/key.pub");     //在Resource目录下创建"key.pub"文件

        outputStream=new FileOutputStream(priPath.getPath());           //输出流拿到key.pri文件输出文件路径
        outputStream.write(rsa.getPrivateKeyBase64().getBytes());       //把数据流写入到key.pri文件中
        outputStream=new FileOutputStream(pubPath.getPath());           //输出流拿到key.pub文件输出文件路径
        outputStream.write(rsa.getPublicKeyBase64().getBytes());        //把数据流写入到key.pub文件中

        outputStream.close();                                           //关闭输出流

    }


}
